//
//  TTDianpuOrderDetailViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/11.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuOrderDetailViewController.h"
#import "TTOrderDetailModel.h"
#import "TTOrderDetailHeaderView.h"
#import "TTCellLabelMiddleModel.h"
#import "TTCellLabelModel.h"
#import "TTCommonViewCell.h"
#import "TTOrderDetailShopViewCell.h"
#import "TTShopCartSubDetailModel.h"

#import "TTDianpuGoodsViewCell.h"
#import "TTDianpuLuoshiViewCell.h"

#import "TTDianpuCommitOrderViewController.h"

#import "TTCommondDataModel.h"

#define cellTypeKey @"cellTypeKey"
#define titleKey @"titleKey"
#define datasKey @"datasKey"
#define sectionHKey @"sectionHKey"

static NSString *goodsCellID = @"goods_cell_id";
static NSString *luoshiCellID = @"luoshi_cell_id";
static NSString *infoCellID = @"info_cell_id";

typedef enum : NSUInteger {
    CellTypeWithShop,
    CellTypeWithInfo,
} CellType;


@interface TTDianpuOrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    TTCellLabelModel *takeGoodsPriceModel;//拿货价
    TTCellLabelModel *totalPriceModel;//总价
    TTCellLabelModel *profitsModel;//利润
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTOrderDetailHeaderView *headerView;

@property (nonatomic, strong) TTOrderDetailModel *detailModel;
@property (nonatomic, strong) NSMutableArray<TTShopCartSubDetailModel *> *shopArray;
///所有商品{Id:<TTShopCartSubDetailModel *>}
@property (nonatomic, strong) NSMutableDictionary *allShopDic;

@property (nonatomic, copy) NSString *orderNo;  // 订单编号

@end

@implementation TTDianpuOrderDetailViewController

- (instancetype)initWithOrderNo:(NSString *)orderNo
{
    self = [super init];
    if (self) {
        self.orderNo = orderNo;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    [self tableView];
    
    [self getNetworkData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSArray *array = dic[datasKey];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger type = [dic[cellTypeKey] intValue];
    @weakify(self)
    if (type == CellTypeWithShop) {
        TTOrderShopModel *model = dic[datasKey][indexPath.row];
        if (model.GoodsType == 1) {
            // 裸石
            TTDianpuLuoshiViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
            cell.model = model;
            [cell.subject subscribeNext:^(TTOrderShopModel *  _Nullable shopModel) {
                @strongify(self)
                [self handleBuyOrder:shopModel];
            }];
            return cell;
        } else {
            TTDianpuGoodsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:goodsCellID];
            cell.model = model;
            [cell.subject subscribeNext:^(TTOrderShopModel *  _Nullable shopModel) {
                @strongify(self)
                [self handleBuyOrder:shopModel];
            }];
            return cell;
        }
    } else if (type == CellTypeWithInfo) {
        
        TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        cell.model = dic[datasKey][indexPath.row];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger type = [dic[cellTypeKey] intValue];
    if (type == CellTypeWithShop) {
        TTOrderShopModel *model = dic[datasKey][indexPath.row];
        return model.h;
    } else if (type == CellTypeWithInfo) {
        if ([[dic[datasKey] firstObject] isKindOfClass:[TTCellLabelMiddleModel class]]) {
            return UITableViewAutomaticDimension;
        } else {
            return 44;
        }
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    return [dic[sectionHKey] floatValue];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length > 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 46)];
        view.backgroundColor = [UIColor whiteColor];
        [LLLineUtilies addLineInView:view startPoint:CGPointZero endPoint:CGPointMake(view.width, 0) lineColor:kSeparatorColor lineWidth:10];
        UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(282828) font:[UIFont fontWithName:@"Source Han Sans CN" size: 14]];
        label.frame = CGRectMake(10, 10, view.width - 20, view.height - 10);
        [view addSubview:label];
        UIColor *bottomLineColor = section == 0 ? [UIColor whiteColor] : kSeparatorColor;
        [LLLineUtilies addLineInView:view startPoint:CGPointMake(10, view.bottom) endPoint:CGPointMake(view.width - 10, view.bottom) lineColor:bottomLineColor];
        return view;
    } else {
        CGFloat h = [dic[sectionHKey] floatValue];
        UIView *view = [UIView new];
        if (h > 0) {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, h)];
            view.backgroundColor = kSeparatorColor;
        }
        return view;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)handleBuyOrder:(TTOrderShopModel *)shopModel
{
    TTShopCartSubDetailModel *detailModel = self.allShopDic[shopModel.Id];
    if (shopModel.isSelected && ![self.shopArray containsObject:detailModel]) {
        [self.shopArray addObject:detailModel];
    } else if (!shopModel.isSelected) {
        [self.shopArray removeObject:detailModel];
    }
    
    [self calculateShopPrice];
    [self.tableView reloadData];
    
    
}

///计算价格
- (void)calculateShopPrice
{
    // 计算价格: 拿货价、总价，利润
    CGFloat takeGoodsPrice = 0, totalPrice = 0, profits = 0;
    for (TTOrderShopModel *shopModel in self.detailModel.Detail) {
        if (shopModel.isSelected) {
            takeGoodsPrice += shopModel.GoodsPrice.floatValue;
            totalPrice += shopModel.PlusShopGoodsPrice.floatValue;
        }
    }
    
    for (TTOrderShopModel *shopModel in self.detailModel.InlayRelateGoodsList) {
        if (shopModel.isSelected) {
            takeGoodsPrice += shopModel.GoodsPrice.floatValue;
            totalPrice += shopModel.PlusShopGoodsPrice.floatValue;
        }
    }
    
    profits += (totalPrice - takeGoodsPrice);
    
    takeGoodsPriceModel.content = [NSString stringWithFormat:@"%.0f", takeGoodsPrice];
    totalPriceModel.content = [NSString stringWithFormat:@"%.0f", totalPrice];
    profitsModel.content = [NSString stringWithFormat:@"%.0f", profits];
}

- (void)getNetworkData
{
//    [MBProgressHUD showLoadingAnimationOnView:self.view];
    co_launch(^{
        // 1. 详情model
        TTOrderDetailModel *detailModel = await([self getOrderDetailData]);
        self.detailModel = detailModel;
        
        if (detailModel == nil) {
//            [MBProgressHUD dismissAnimationOnView:self.view];
            [self.tableView reloadData];
            return;
        }
        
//        [MBProgressHUD dismissAnimationOnView:self.view];
        
        [self.shopArray removeAllObjects];
        [self.allShopDic removeAllObjects];
        // 计算高度
        for (TTOrderShopModel *shopModel in detailModel.Detail) {
            [self calculateCellHeightWithShopModel:shopModel];
            // 转化model
            TTShopCartSubDetailModel *detailModel = [TTCommondDataModel orderShopModelToShopCartSubDetailModel:shopModel];
            shopModel.isSelected = shopModel.SysStatus.intValue == 1;
            if (shopModel.SysStatus.intValue == 1) {
                [self.shopArray addObject:detailModel];
            }
            [self.allShopDic setObject:detailModel forKey:detailModel.Id];
        }
        for (TTOrderShopModel *shopModel in detailModel.InlayRelateGoodsList) {
            [self calculateCellHeightWithShopModel:shopModel];
            // 转化model
            TTShopCartSubDetailModel *detailModel = [TTCommondDataModel orderShopModelToShopCartSubDetailModel:shopModel];
            shopModel.isSelected = shopModel.SysStatus.intValue == 1;
            if (shopModel.SysStatus.intValue == 1) {
                [self.shopArray addObject:detailModel];
            }
            [self.allShopDic setObject:detailModel forKey:detailModel.Id];
        }
        
        [self setupBottomView];
        
        [self.headerView setModel:detailModel isFromDianpu:YES];
        [self.headerView layoutIfNeeded];
        
        self.tableView.tableHeaderView = self.headerView;
        
        [self setupDatasWithModel:detailModel];
        
        [self calculateShopPrice];
        
        [self.tableView reloadData];
        
        if (detailModel.OrderState.intValue == 0) {
            UIButton *rightBtn = [UIButton createButtonWithTitle:@"取消订单" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:self action:@selector(cancelOrderAction)];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
            
        }
        
    });
}


// 取消订单
- (void)cancelOrderAction
{
    NSDictionary *dic = @{
        @"param.orderNo" : self.detailModel.OrderNo,
        @"param.relationName" : [TTLoginSingle sharedSingle].loginModel.RealName
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:plusCancelOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 通知我的页面数字刷新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPageCountNotify" object:nil];
        // 通知店铺管理页面刷新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreashDatas" object:nil];
        // 订单管理刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setDianpuPageRefreshStatusNotify" object:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 获取详情数据
- (COPromise *)getOrderDetailData
{
    COPromise *promise = [COPromise promise];
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:plusOrderDetail_api parameters:@{@"param.orderNo" : self.orderNo} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        TTOrderDetailModel *detailModel = [TTOrderDetailModel modelWithJSON:responseObject];
        
        [promise fulfill:detailModel];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}


// 计算cell高度
- (void)calculateCellHeightWithShopModel:(TTOrderShopModel *)shopModel
{
    CGFloat cellImageH = 65 * kScale + 40;
    
    if (shopModel.GoodsType == 1) {
        shopModel.h = cellImageH;
    } else {
        NSData *data = [shopModel.GoodsDescribe dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *describe = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *content = [describe componentsJoinedByString:@"\n"];
        CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 95 * kScale - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 68;
        
        contentH = contentH < cellImageH ? cellImageH : contentH;
        
        shopModel.h = contentH;
        //定制的
        if (shopModel.GoodsType == 2) {
            shopModel.h = contentH + 30;
        }
    }
    
}

// 联系客户
- (void)contactKehu
{
    [self.detailModel.ReceiverMobile callPhone];
}

// 下单
- (void)xiadanBtnClick
{
    if (self.detailModel.OrderState.intValue == 1) {
        // 确认已付
        @weakify(self)
        [[LLNetworkManagerTool sharedManager] postUrlString:plusConfirmPaid_api parameters:@{@"param.orderNo" : self.detailModel.OrderNo} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            @strongify(self)
            [self getNetworkData];
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {

        } showLoadingInView:self.view];
    } else {
        if (self.shopArray.count == 0) {
            [self.view makeToast:@"请选择商品下单"];
            return;
        }
        // 去下单
        TTDianpuCommitOrderViewController *commitVC = [[TTDianpuCommitOrderViewController alloc] initWithShopArray:self.shopArray plusShopCustomerName:self.detailModel.ReceiverName plusShopOrderNo:self.detailModel.OrderNo sumGoodsPrice:self.detailModel.SumGoodsPrice];
        [self.navigationController pushViewController:commitVC animated:YES];
    }
}

- (void)setupBottomView
{
    UIButton *phoneBtn = [UIButton createButtonWithTitle:@" 联系买家" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:18] backgroundColor:[UIColor whiteColor] target:self action:@selector(contactKehu)];
    [phoneBtn setImage:[UIImage imageNamed:@"zisephone"] forState:UIControlStateNormal];
    [self.view addSubview:phoneBtn];
    [phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(self.view.width * 0.5);
    }];
    
    
    NSString *normalTitle = self.detailModel.OrderState.intValue == 0 ? @"下单" : @"确认已付";
    UIImage *disabledImage = [UIImage imageWithColor:UIColorHex(999999)];
    UIButton *xiadanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [xiadanBtn setBackgroundImage:[UIImage imageNamed:@"login_btn_abled"] forState:UIControlStateNormal];
    [xiadanBtn setBackgroundImage:disabledImage forState:UIControlStateDisabled];
    [xiadanBtn setTitle:normalTitle forState:UIControlStateNormal];
    [xiadanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [xiadanBtn setTitle:@"确认已付" forState:UIControlStateDisabled];
    [xiadanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [xiadanBtn addTarget:self action:@selector(xiadanBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:xiadanBtn];
    [xiadanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.width.height.equalTo(phoneBtn);
        make.left.equalTo(phoneBtn.mas_right);
    }];
    
    xiadanBtn.enabled = self.detailModel.OrderState.intValue <= 1;
}

- (void)setupDatasWithModel:(TTOrderDetailModel *)model
{
    NSMutableArray *shopsArray = [NSMutableArray arrayWithArray:model.Detail];
    if (model.InlayRelateGoodsList.count > 0) {
        [shopsArray addObjectsFromArray:model.InlayRelateGoodsList];
    }
    
    takeGoodsPriceModel = [TTCellLabelModel setModelWithTitle:@"订单拿货价" content:[NSString stringWithFormat:@"￥%@", model.SumGoodsPrice] contentColor:UIColorHex(FF1F1F)];
    totalPriceModel = [TTCellLabelModel setModelWithTitle:@"订单应付总金额" content:[NSString stringWithFormat:@"￥%@", model.PlusShopShouldPaySumPrice] contentColor:UIColorHex(FF1F1F)];
    profitsModel = [TTCellLabelModel setModelWithTitle:@"订单利润" content:[NSString stringWithFormat:@"￥%@", model.ProfitPrice] contentColor:UIColorHex(FF1F1F)];
    
    NSArray *arr = @[
        @{
            cellTypeKey : @(CellTypeWithShop),
            titleKey : @"商品列表",
            datasKey : shopsArray,
            sectionHKey : @50
        },
        @{
            cellTypeKey : @(CellTypeWithInfo),
            sectionHKey : @0,
            datasKey : @[takeGoodsPriceModel, totalPriceModel, profitsModel]
        },
        
        @{
            cellTypeKey : @(CellTypeWithInfo),
            sectionHKey : @10,
            datasKey : @[
                    [TTCellLabelMiddleModel setModelWithTitle:@"订单号:" midText:model.OrderNo],
                    [TTCellLabelMiddleModel setModelWithTitle:@"下单时间:" midText:model.CreateTime],
                    [TTCellLabelMiddleModel setModelWithTitle:@"备注:" midText:model.Remark.length == 0 ? @"无" : model.Remark]
            ]
        }
    ];
    
    self.dataArray = arr.mutableCopy;
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.emptyImageName = @"tao_nodata";
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _tableView.separatorColor = kSeparatorColor;
        [_tableView registerClass:[TTDianpuGoodsViewCell class] forCellReuseIdentifier:goodsCellID];
        [_tableView registerClass:[TTDianpuLuoshiViewCell class] forCellReuseIdentifier:luoshiCellID];
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:infoCellID];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-45);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (TTOrderDetailHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [TTOrderDetailHeaderView orderDetailHeaderView];
    }
    return _headerView;
}


- (NSMutableArray<TTShopCartSubDetailModel *> *)shopArray
{
    if (!_shopArray) {
        _shopArray = [NSMutableArray array];
    }
    return _shopArray;
}

- (NSMutableDictionary *)allShopDic
{
    if (!_allShopDic) {
        _allShopDic = [NSMutableDictionary dictionary];
    }
    return _allShopDic;
}

@end
